// pages/me/me.js
const app = getApp();
Page({
    data: {
      refreshed: false, // 将本属性设置为true，收起下拉刷新，可多次设置为true（即便原来已经是true了）
      StatusBar: app.globalData.StatusBar,
      CustomBar: app.globalData.CustomBar,
      screenHeight: app.globalData.screenHeight,
      userInfo:{},
      roleList:[],//摘出来用户的权限信息
      shareImage:'',
      paintPallette:{}, //绘制分享内容图片
      msgNumber:{
        noticeNums:0,
        dealerUserApplyNums:0,
        totalNums:0
      },
      priceList:[]
    },
      doNothing(){},
      onImgOK(e) {
        console.log('分享图生成完毕');
        this.imagePath = e.detail.path;
        wx.hideLoading();
        this.setData({
          shareImage: this.imagePath,
        });
      },
      copyText: function (e) {
        wx.setClipboardData({
          data: e.currentTarget.dataset.text,
          success: function (res) {
            wx.getClipboardData({
              success: function (res) {
                wx.showToast({
                  title: '复制成功'
                })
              }
            })
          }
        })
      },
      openCustomerServiceChat(){
        app.openCustomerServiceChat();
      },
      showShareModal(){
        app.showLoading('正在展开名片');
        let userInfo = this.data.userInfo;
        if(undefined != userInfo.custMager){
          let paintPallette = {
            width: '1312rpx',
            height: '1840rpx',
            background: '#fff',
            borderRadius: '24rpx',
            views:[
              {
                type: 'text',
                text: userInfo.custMager.userTitle,
                css: {
                  fontSize: '64rpx',
                  top: `72rpx`,
                  left: `528rpx`,
                  color: `#8A8A8A`,
                }
              },
              {
                type: 'rect',
                css: {
                  width: '1168rpx',
                  height: '2rpx',
                  color: '#E4E5E4',
                  top: `204rpx`,
                  left: `72rpx`,
                }
              },
              {
                type: 'image',
                url: userInfo.custMager.logoUrl,
                css: {
                  width: `512rpx`,
                  height: `512rpx`,
                  top:`280rpx`,
                  left: `400rpx`,
                  borderRadius:`336px`,
                }
              },
              {
                type: 'text',
                text: userInfo.custMager.userName,
                css: {
                  fontSize: '56rpx',
                  top: `804rpx`,
                  width: `1312rpx`,
                  textAlign: 'center',
                  color: `#101010`,
                }
              },
              {
                type: 'text',
                text: userInfo.custMager.userMobile,
                css: {
                  fontSize: '48rpx',
                  top: `880rpx`,
                  width: `1312rpx`,
                  textAlign: 'center',
                  color: `#bababa`,
                }
              },
              {
                type: 'image',
                url: userInfo.custMager.qrCode,
                css: {
                  width: `730rpx`,
                  height: `730rpx`,
                  top:`968rpx`,
                  left: `320rpx`,
                }
              },
            ]
          };
          if(this.getTabBar()){
            this.getTabBar().hideTabbar();
          }
          this.setData({
            'paintPallette':paintPallette,
            'modalName': 'shareModal'
          });
        }else{
          wx.hideLoading();
          app.error('您当前没有客户经理哦~');
        }
      },
      hideModal(e) {
        if(this.getTabBar()){
          this.getTabBar().showTabbar();
        }
        this.setData({
          modalName: null
        })
      },
      // 保存分享的图片
      saveShareImage() {
        let self = this;
        //图片保存到本地相册
        wx.saveImageToPhotosAlbum({
          filePath: self.data.shareImage,
          //授权成功，保存图片
          success: function (data) {
            app.success('已保存到您的相册');
          },
          //授权失败
          fail: function (err) {
            console.log(err);
            if (err.errMsg != 'saveImageToPhotosAlbum:fail cancel') { //重新授权弹框确认
              wx.showModal({
                title: '提示',
                content: '您好，请先授权再保存此图片。',
                showCancel: false,
                success(res) {
                  if (res.confirm) { //重新授权弹框用户点击了确定
                    wx.openSetting({ //进入小程序授权设置页面
                      success(settingdata) {
                        console.log(settingdata)
                        if (settingdata.authSetting['scope.writePhotosAlbum']) { //用户打开了保存图片授权开关
                          wx.saveImageToPhotosAlbum({
                            filePath: self.data.shareImage,
                            success: function (data) {
                              app.success('已保存到您的相册');
                            },
                          })
                        } else { //用户未打开保存图片到相册的授权开关
                          wx.showModal({
                            title: '温馨提示',
                            content: '授权失败，请稍后重新获取',
                            showCancel: false,
                          })
                        }
                      }
                    })
                  }
                }
              })
            }
          }
        })
      },
      // 打客户经理电话
      callCust(e){
        wx.makePhoneCall({
          phoneNumber: e.currentTarget.dataset.phone,
          success:function(){},
          fail:function(){}
        })
      },
      jumpToWantBuy(){
        if (2 == this.data.userInfo.accountStatus) {
          if (this.isHaveAuth('manageWantBuy')) {
            wx.navigateTo({
              url: '/pages/me/wantBuy/wantBuy',
            })
          }else{
            app.error('您无权操作');
          }
        }
      },
      jumpToEdit(){
        if(2 == this.data.userInfo.accountStatus){
          wx.navigateTo({
            url: '/pages/me/editSelf/editSelf',
          })
        }
      },
      jumpToNotice(){
        wx.navigateTo({
          url: '/pages/me/notice/notice',
        })
      },
      jumpToCarQueryRecord(){
        wx.navigateTo({
          url: '/pages/carQueryRecord/carQueryRecord',
        })
      },
      jumpToDepositRecord(){
        wx.navigateTo({
          url: '/pages/me/depositRecord/depositRecord',
        })
      },
      jumpToReportApplication(){
        wx.navigateTo({
          url: '/pages/carQueryRecord/reportApplication/reportApplication',
        })
      },
      jumpToWallet(){
        wx.navigateTo({
          url: '/pages/me/wallet/wallet',
        })
      },
      // 跳转到管理一口价的页面
      jumpToSeb(){
        if (this.isHaveAuth('manageSecondBatch')) {
          wx.navigateTo({
            url: '/pages/me/secondBatch/secondBatch',
          })
        }else{
          app.error('您无权操作');
        }
      },
      // 跳转到管理拍卖
      jumpToAuction(){
        if (this.isHaveAuth('manageAuction')) {
          wx.navigateTo({
            url: '/pages/me/auction/auction',
          })
        }else{
          app.error('您无权操作');
        }
      },
      // 跳转到公司管理界面
      jumpToManageDealer(){
        if (this.isHaveAuth('manageDealer')) {
          wx.navigateTo({
            url: '/pages/me/manageDealer/manageDealer',
          })
        }else{
          app.error('您无权操作');
        }
      }, // 跳转到公司管理界面
      jumpToManageTeam(){
        if (this.isHaveAuth('manageTeam')) {
          wx.navigateTo({
            url: '/pages/me/manageTeam/manageTeam',
          })
        }else{
          app.error('您无权操作');
        }
      },
      // 跳转到出价管理
      jumpToOfferPrice(){
        if (this.isHaveAuth('viewCar')) {
          wx.navigateTo({
            url: '/pages/me/offerPrice/offerPrice',
          })
        }else{
          app.error('您无权操作');
        }
      },
      isHaveAuth(authIcon){
        let index = this.data.roleList.indexOf(authIcon);
        return index != -1?true:false;
      },
      makePhoneCall(){
          wx.makePhoneCall({
              phoneNumber: app.globalData.customerService,
              success:function(){},
              fail:function(){}
          })
      },
      pullDownRefresh(){
        this.lifeInit();
        let self = this;
        setTimeout(() => {
          self.setData({
            'refreshed': true
          })
        }, 1000);
      },
      // 真正的初始化页面。
      lifeInit(){
        this.InitUserStatus();
        app.globalData.meComponentLoadTime = new Date();
      },
      async InitUserStatus(){
        await app.checkToken();
        let accountStatus = app.accountStatus;
        // 回填权限列表。
        let userInfo = app.globalData.userInfo;
        if (undefined != userInfo.roleList && null != userInfo.roleList) {
          this.setData({
            roleList: userInfo.roleList
          });
        }
        this.setData({
          accountStatus: accountStatus,
          userInfo:userInfo
        });
        if(this.getTabBar()){
          this.getTabBar().setData({
            roleList:userInfo.roleList,
            accountStatus:accountStatus,
            userInfo:userInfo,
            remindList:userInfo.remindList
          })
        }
        this.loadDealerInfo();
        this.loadMsgUnreadStat();
        this.dealerAmountRechargePriceList();
      },
      loadMsgUnreadStat(){
        app.sHttp.msgUnreadStat().then(res =>{
          this.setData({
            'msgNumber': res.result
          });
          if(this.getTabBar()){
            this.getTabBar().setData({
              'msgNumber': res.result
            })
          }
        },err=>{
        })
      },  // 加载下车商的信息。
      loadDealerInfo(){
        if(Object.keys(app.globalData.dealerInfo).length === 0){
          app.sHttp.dealerInfo().then(res =>{
            if(res.result.city == '市辖区'){
              res.result.city = res.result.province;
            }
            app.globalData.dealerRegion = [res.result.province, res.result.city , res.result.district];
            app.globalData.dealerInfo = res.result;
            // 并且把地址填充到
            // app.globalData.defaultCity = res.result.city || '全国';
          },err=>{
          })
        }
      },
      dealerAmountRechargePriceList(){
        if(app.globalData.priceList.length === 0){
          app.sHttp.dealerAmountRechargePriceList().then(res=>{
            this.setData({
              'priceList': res.priceList
            });
            app.globalData.priceList = res.priceList;
          },err=>{
          })
        }else{
          this.setData({
            'priceList': app.globalData.priceList
          });
        }
      },
      onShow() {
        // 是否需要请求
        this.lifeInit();
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
          this.getTabBar().setData({
            selected: 4
          })
        }
      },
      onShareAppMessage(){
        let userName = this.data.userInfo.userName;
        let uid = this.data.userInfo.userId;
        return {
          title: userName + ' 喊你来看车了',
          path: '/pages/login/login?bsid='+uid,
          imageUrl: '/images/share/shareimage.png'
        }
      },
      
    jumpToUserAgreement(){
      wx.navigateTo({
        url: '/pages/publicPage/userAgreement/userAgreement',
      })
    },
})
